class RolesController < ApplicationController

	load_and_authorize_resource

	def new
	@user=User.find(params[:id])
	@role=Role.new
	end

	def index


	end


	def show

	end
	def create
		usr_ids=params[:users_id]
		# 全选框
		all= params[:all]
		# 全选的role
		add_to_all=params[:add_all]
		user_role=params[:user]["1"]
		# 分别添加属性
		if usr_ids.present?  && all.blank?
			usr_ids.each do |item|
			id=item.to_i
		  user=User.find(id)
			if params[:user][item].present?
				user.roles.create!(name: params[:user][item])
			end
			end
		end
		# 全选中添加属性
		if   add_to_all.present? && all.present?
			# id转化为integer
			usr_ids=usr_ids.each_with_index { |item, i| usr_ids[i]=item.to_i}
			usrs=	User.where(id: usr_ids)
			usrs.each do |user|
				@role=user.roles.create!(name: all)
			end
		end
		redirect_to  action: "search"
	end


	def destroy

	end

	def update


	end

	def search
		search_params = {
			query: {
				simple_query_string: {
					query: params[:q],
					default_operator: 'AND',
					minimum_should_match: '50%',
					fields: ['email', 'name', 'login']
				}
			},
			_source: ['id', 'name','email'],
			highlight: {
				pre_tags: ["[h]"],
				post_tags: ["[/h]"],
				fields: { email: {}, name: {}, login: {} }
			}
		}
		@all_users=User.all.select("name, email,id,avatar").paginate(page: params[:page],per_page: 30)

		if params[:q].present?
			@users = Elasticsearch::Model.search(search_params, [User]).paginate(page: params[:page], per_page: 30)
		end
		#   @result=User.search(params[:q])

	end

	def fetch_user
		@user= User.find_by(email: params[:user_email])

		respond_to do |format|

			format.html redirect_to action: "new"
			format.js
		end

	end

	private
		def required_params
			params.require(:role).permit(:name)
		end

end
